#define _CRT_SECURE_NO_WARNINGS
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(vector<int>& preorder, vector<int>& inorder,
        int& prei, int inBegin, int inEnd)
    {
        if (inBegin > inEnd)
            return nullptr;
        int rooti = inBegin;
        //[0, rooti-1] rooti [rooti+1, size]
        while (rooti <= inEnd)
        {
            if (preorder[prei] == inorder[rooti])
                break;
            ++rooti;
        }

        TreeNode* root = new TreeNode(preorder[prei++]);
        root->left = _buildTree(preorder, inorder, prei, inBegin, rooti - 1);
        root->right = _buildTree(preorder, inorder, prei, rooti + 1, inEnd);
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int prei = 0;
        return _buildTree(preorder, inorder,
            prei, 0, inorder.size() - 1);
    }
};